Sample codes > Multiple vendors
Multiple vendors
As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.
For the sample prompts here, your might get different responses since AI models have random elements.
AI Prompt:
I'd like a shipping rate calculator function.
If the items product tags array field includes "etsy", use ETSY shipping rates.
The items product tags array can be accessed in the "product" field after enriching the input data.
Enrich the data with metafield namespace "shop" with size 10, and metafield namespace "market" with size 5.
The etsy product id and etsy shop id for each items is saved in the data items object metafield in the object "shop" with keys named "esty_product_id" and "etsy_shop_id", respectively.
If the items product tags array field includes "dhgate", use DHgate shipping rates.
The product id for each dhgate items is saved in the data items object metafield in the object "shop" with key named "dhgate_product_id".
In case of multiple DHgate rates option for an item, take the rate option with the minimum rate price.
If the items product tags array field includes "Dsers", use Dsers shipping rates.
The Dsers product id for each items is saved in the data items object metafield in the object "market" with keys named "dsers_product_id".
The Dsers email and password can be access from the environment variable object with the keys "dsers_email" and "dsers_password", respectively.
In case of multiple Dsers rates option for an item, take the rate option with the minimum rate price.
If items tags do not include "etsy", "dhgate" and "Dsers", calculate the distance in km between the origin and destination using Google Distance Matrix API (in driving mode) and the resulting distance in km is multiplied by 0.02 cents for shipping cost.
You will implement the Google Distance Matrix distance calculator. The Google API access key is provided in the env object of the shipping rate calculator function argument with key name "google_api_key".
If the total items price is more than $500, provide 5% discount from the shipping cost. The total item price is the sum of each item price.
If there are multiple shipping rates, the function should combine the rates by adding each rates price and generate one shipping rate. For this case, the maximum delivery date is 8 days from now, and the minimum delivery date is 5 days from now.
AI Output:
import { enrichItemDetails } from "./modules.js";
import { DHgate } from "./modules.js";
import { Etsy } from "./modules.js";
import { Dsers } from "./modules.js";
export async function calculateShippingRates(DATA, env) {
try {
// Enrich the data with metafield namespace "shop" with size 10, and metafield namespace "market" with size 5.
DATA = await enrichItemDetails(DATA, [
{ namespace: "shop", size: 10 },
{ namespace: "market", size: 5 },
]);
// Initialize the rates array.
let rates = [];
// Loop through the items.
for (const item of DATA.items) {
// Check if the item's product tags array field includes "etsy".
if (item.product.tags.includes("etsy")) {
// Get the Etsy product id and shop id from the item's metafield.
const etsyProductId = item.metafields.shop.etsy_product_id;
const etsyShopId = item.metafields.shop.etsy_shop_id;
// Create an Etsy instance.
const etsy = new Etsy(DATA.destination, DATA.currency);
// Get the Etsy shipping rates.
const etsyRates = await etsy.getRates([
{ etsy_product_id: etsyProductId, etsy_shop_id: etsyShopId, quantity: item.quantity },
]);
// Add the Etsy rates to the rates array.
rates = rates.concat(etsyRates);
}
// Check if the item's product tags array field includes "dhgate".
else if (item.product.tags.includes("dhgate")) {
// Get the DHgate product id from the item's metafield.
const dhgateProductId = item.metafields.shop.dhgate_product_id;
// Create a DHgate instance.
const dhgate = new DHgate(DATA.destination, DATA.currency);
// Get the DHgate shipping rates.
const dhgateRates = await dhgate.getRates([
{ dhgate_product_id: dhgateProductId, quantity: item.quantity },
]);
// Get the minimum rate price from the DHgate rates.
const minDhgateRatePrice = Math.min(...dhgateRates.map((rate) => rate.total_price));
// Add the DHgate rate with the minimum rate price to the rates array.
rates.push(
dhgateRates.find((rate) => rate.total_price === minDhgateRatePrice)
);
}
// Check if the item's product tags array field includes "Dsers".
else if (item.product.tags.includes("Dsers")) {
// Get the Dsers product id from the item's metafield.
const dsersProductId = item.metafields.market.dsers_product_id;
// Create a Dsers instance.
const dsers = new Dsers(
env.dsers_email,
env.dsers_password,
DATA.destination,
DATA.currency
);
// Get the Dsers shipping rates.
const dsersRates = await dsers.getRates([
{ dsers_product_id: dsersProductId, quantity: item.quantity },
]);
// Get the minimum rate price from the Dsers rates.
const minDsersRatePrice = Math.min(...dsersRates.map((rate) => rate.total_price));
// Add the Dsers rate with the minimum rate price to the rates array.
rates.push(
dsersRates.find((rate) => rate.total_price === minDsersRatePrice)
);
}
// If the item's product tags array field does not include "etsy", "dhgate", or "Dsers", calculate the distance in km between the origin and destination using Google Distance Matrix API (in driving mode) and the resulting distance in km is multiplied by 0.02 cents for shipping cost.
else {
// Get the origin and destination addresses.
const originAddress = `${DATA.origin.address1}, ${DATA.origin.city}, ${DATA.origin.province}, ${DATA.origin.country}`;
const destinationAddress = `${DATA.destination.address1}, ${DATA.destination.city}, ${DATA.destination.province}, ${DATA.destination.country}`;
// Calculate the distance between the origin and destination using Google Distance Matrix API.
const distanceResponse = await fetch(
`https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=${originAddress}&destinations=${destinationAddress}&key=${env.google_api_key}`
);
const distanceData = await distanceResponse.json();
// Get the distance in km.
const distanceInKm = distanceData.rows[0].elements[0].distance.value / 1000;
// Calculate the shipping cost.
const shippingCost = distanceInKm * 0.02;
// Add the shipping cost to the rates array.
rates.push({
service_name: "Google Distance Matrix API",
service_code: "google_distance_matrix_api",
total_price: shippingCost * 100,
description: "Shipping cost calculated using Google Distance Matrix API.",
currency: DATA.currency,
min_delivery_date: "",
max_delivery_date: "",
});
}
}
// If the total items price is more than $500, provide 5% discount from the shipping cost.
if (DATA.items.reduce((acc, item) => acc + item.price * item.quantity, 0) > 50000) {
rates = rates.map((rate) => ({
...rate,
total_price: Math.round(rate.total_price * 0.95),
}));
}
// If there are multiple shipping rates, the function should combine the rates by adding each rates price and generate one shipping rate. For this case, the maximum delivery date is 8 days from now, and the minimum delivery date is 5 days from now.
if (rates.length > 1) {
const combinedRate = {
service_name: "Combined Rates",
service_code: "combined_rates",
total_price: rates.reduce((acc, rate) => acc + rate.total_price, 0),
description: "Combined shipping rates.",
currency: DATA.currency,
min_delivery_date: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
max_delivery_date: new Date(Date.now() + 8 * 24 * 60 * 60 * 1000).toISOString(),
};
rates = [combinedRate];
}
// Return the rates array.
return { rates };
} catch (error) {
// In case of errors, return a rate with price equals to null, and other rate fields set to empty string.
return {
rates: [
{
service_name: "",
service_code: "",
total_price: null,
description: "",
currency: "",
min_delivery_date: "",
max_delivery_date: "",
},
],
};
}
}